from pyrogram import filters
from pyrogram.types.messages_and_media import Message

from app import app
import app.libs.create_transaction as ct


def format_byte_size(size_bytes):
    if size_bytes == 0:
        return "0 B"
    units = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]
    i = 0
    while size_bytes >= 1024 and i < len(units) - 1:
        size_bytes /= 1024.0
        i += 1
    return "{:.2f} {}".format(size_bytes, units[i])


@app.on_message(filters.me & filters.command("ct1"))
async def create_transaction(client, message: Message):
    try:
        price = float(message.command[1])
        bonus = [int(b) for b in (message.command[2]).split(",")]
        amount = int(message.command[3])
    except Exception as e:
        return await message.reply(
            f"格式有误! 请参照以下格式:\n/ct1 单价 金额(万)[,金额(万),...] 数量\n`/ct 100 60 1`"
        )
    m = "正在发布..."
    await message.edit(m)
    for b in bonus:
        amount = await ct.create(1, bonus=10000 * b, upload=price * b, n=amount)
        if amount > 0:
            m += f"\n单价{price} 出售{b}万灵石 获得{format_byte_size(price*b*1024*1024*1024)}上传 上架{amount}个"
            await message.edit(m)


@app.on_message(filters.me & filters.command("ct2"))
async def create_transaction(client, message: Message):
    try:
        price = float(message.command[1])
        bonus = [int(b) for b in (message.command[2]).split(",")]
        amount = int(message.command[3])
    except Exception as e:
        return await message.reply(
            f"格式有误! 请参照以下格式:\n/ct2 单价 金额(万)[,金额(万),...] 数量\n`/ct 76.5 60 1`"
        )
    m = "正在发布..."
    await message.edit(m)
    for b in bonus:
        amount = await ct.create(2, bonus=10000 * b, upload=price * b, n=amount)
        if amount > 0:
            m += f"\n单价{price} 出售上传{format_byte_size(price*b*1024*1024*1024)} 金额{b}万灵石 上架{amount}个"
            await message.edit(m)
